<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input
            v-model="queryParams.keywords"
            placeholder="品牌名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <div class="table-operation">
        <el-button type="success" plain icon="Plus" @click="handleAdd">新增</el-button>
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="selectedItems.length === 0"
          @click="handleBatchDelete"
        >
          删除
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="brandList"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="品牌名称" prop="name" align="center" />
        <el-table-column label="品牌logo" align="center">
          <template #default="scope">
            <el-image
              v-if="scope.row.logo"
              :src="scope.row.logo"
              style="width: 80px; height: 40px"
              fit="contain"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          label="介绍"
          prop="description"
          :show-overflow-tooltip="true"
          align="center"
        />
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.showStatus === 0" type="success">显示</el-tag>
            <el-tag v-else type="info">不显示</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="sort" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button type="primary" link icon="Edit" @click="handleUpdate(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link icon="Delete" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        :total="total"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改品牌对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="50vw" append-to-body>
      <el-form ref="brandFormRef" :model="form" :rules="rules" label-width="auto">
        <el-form-item label="品牌名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入品牌名称" />
        </el-form-item>
        <el-form-item label="品牌logo" prop="logo">
          <div class="logo-upload-wrapper">
            <SingleImageUpload v-model="form.logo" dir="guli-mall/brand/"/>
            <el-text type="info" size="small" class="el-upload__tip logo-upload-tip">
              支持jpg/png文件，且不超过2MB
            </el-text>
          </div>
        </el-form-item>
        <el-form-item label="介绍" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="检索首字母" prop="firstLetter">
          <el-input v-model="form.firstLetter" placeholder="请输入检索首字母" maxlength="1" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" controls-position="right" />
        </el-form-item>
        <el-form-item label="显示状态" prop="showStatus">
          <el-radio-group v-model="form.showStatus">
            <el-radio :label="0">显示</el-radio>
            <el-radio :label="1">不显示</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="dialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import ProductBrandAPI, { Brand, BrandPageReqVo } from "@/api/product/brand.api";
import SingleImageUpload from "@/components/MyUpload/SingleImageUpload.vue";

// 品牌列表
const brandList = ref<Brand[]>([]);
// 选中的项
const selectedItems = ref<Brand[]>([]);
// 总数
const total = ref(0);
// 加载状态
const loading = ref(false);
// 表单引用
const brandFormRef = ref<FormInstance>();

// 查询参数
const queryParams = ref<BrandPageReqVo>({
  pageNum: 1,
  pageSize: 10,
  keywords: "",
});

// 对话框状态
const dialog = ref({
  visible: false,
  title: "",
});

// 表单数据
const form = ref<Brand>({
  brandId: undefined,
  name: "",
  logo: "",
  description: "",
  showStatus: "0",
  firstLetter: "",
  sort: "0",
});

// 表单校验规则
const rules = ref<FormRules>({
  name: [{ required: true, message: "品牌名称不能为空", trigger: "blur" }],
  firstLetter: [{ pattern: /^[a-zA-Z]$/, message: "首字母必须是字母", trigger: "blur" }],
  sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
});

onMounted(() => {
  getList();
});

// 获取品牌分页列表
const getList = async () => {
  loading.value = true;
  try {
    const res = await ProductBrandAPI.getBrandPage({
      pageNum: queryParams.value.pageNum,
      pageSize: queryParams.value.pageSize,
      keywords: queryParams.value.keywords,
    });
    brandList.value = res.records;
    total.value = res.total || 0;
  } finally {
    loading.value = false;
  }
};

// 表格多选框选中数据
const handleSelectionChange = (selection: Brand[]) => {
  selectedItems.value = selection;
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

// 重置按钮操作
const resetQuery = () => {
  queryParams.value.keywords = "";
  handleQuery();
};

// 新增按钮操作
const handleAdd = () => {
  resetForm();
  dialog.value.visible = true;
  dialog.value.title = "添加品牌";
};

// 修改按钮操作
const handleUpdate = (row: Brand) => {
  resetForm();
  dialog.value.visible = true;
  dialog.value.title = "修改品牌";
  Object.assign(form.value, row);
};

// 提交表单
const submitForm = async () => {
  if (!brandFormRef.value) return;
  await brandFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      if (form.value.brandId) {
        await ProductBrandAPI.updateBrand(form.value);
        ElMessage.success("修改成功");
      } else {
        await ProductBrandAPI.addBrand(form.value);
        ElMessage.success("新增成功");
      }
      dialog.value.visible = false;
      await getList();
    }
  });
};

// 删除按钮操作
const handleDelete = (row: Brand) => {
  ElMessageBox.confirm("确认要删除该品牌吗?", "警告", {
    type: "warning",
  })
    .then(async () => {
      await ProductBrandAPI.removeBrandByIds([row.brandId!]);
      ElMessage.success("删除成功");
      await getList();
    })
    .catch(() => {});
};

// 批量删除
const handleBatchDelete = () => {
  const ids = selectedItems.value.map((item) => item.brandId!);
  if (ids.length === 0) {
    ElMessage.warning("请选择要删除的品牌");
    return;
  }
  ElMessageBox.confirm("确认要删除选中的品牌吗?", "警告", {
    type: "warning",
  })
    .then(async () => {
      await ProductBrandAPI.removeBrandByIds(ids);
      ElMessage.success("删除成功");
      await getList();
    })
    .catch(() => {});
};

// 重置表单
const resetForm = () => {
  form.value.brandId = undefined;
  form.value.name = "";
  form.value.logo = "";
  form.value.description = "";
  form.value.showStatus = "0";
  form.value.firstLetter = "";
  form.value.sort = "0";
};
</script>

<style scoped lang="scss">
.table-operation {
  margin-bottom: 20px;
}

.avatar-uploader {
  :deep(.el-upload) {
    position: relative;
    overflow: hidden;
    cursor: pointer;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;

    &:hover {
      border-color: #409eff;
    }
  }
}

.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  font-size: 28px;
  line-height: 178px;
  color: #8c939d;
  text-align: center;
}

.avatar {
  display: block;
  width: 178px;
  height: 178px;
}

.logo-upload-wrapper {
  display: flex;
  flex-direction: column;
  align-items: flex-start;

  .avatar-uploader {
    margin-bottom: 8px;
  }

  .logo-upload-tip {
    margin-left: 2px;
    color: #909399;
  }
}
</style>
